
const {ccclass, property} = cc._decorator;

@ccclass
export default class Helloworld extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property(cc.Label)
    labelscore: cc.Label = null;

    @property(cc.Label)
    gameoverLabel:cc.Label = null;

    speed = 0;
    num = 0;
    girdArr = {};
    score = 0;
    flag =1;
    id = 0;

    start () {
        // init logic
        this.labelscore.string = "0";
    }

    update(){
        if(this.num>1000){
            this.num = 0;
        }else{
            this.num += 1;
        }
        if (this.num%60==0&&this.flag ==1){
            this.id += 1;
            cc.loader.loadRes("grid", cc.Prefab, (err, prefab)=>{
                if (err) {
                    throw err;
                } else {
                    let node = cc.instantiate(prefab);
                    node.parent = this.node;
                    node.x = 400 - Math.random()*800;
                    node.y = 300; 
                    let atype = 1;
                    if (Math.random()>0.5){
                        atype = 2;
                    }
                    let id = this.id.toString();
                    this.girdArr[this.id.toString()] = node;
                    node.getComponent("Grid").setData(id,atype,this.clickGrid.bind(this,id,atype));
                    //let jumpDown = cc.moveBy(20, cc.v2(0, -900)).easing(cc.easeCubicActionIn());
                    let jumpDown = cc.moveBy(20, cc.v2(0, -900));
                    node.runAction(jumpDown);
                }
            }) 
        }
    }

    clickGrid(id:string,atype:number){
        if (this.flag == 1){
            if(atype == 1){
                this.score += 1;
                this.labelscore.string = this.score.toString();
                cc.log(444);
                this.girdArr[id].destroy();
            }else{
                this.gameOver();
            }
        }
    }

    gameOver(){
        this.gameoverLabel.node.x = 0;
        this.flag = 0;
        for(var key in this.girdArr){
            this.girdArr[key].stopAllActions();
        }
        
    }

    startAgain(){
        this.gameoverLabel.node.x = 10000;
        this.flag = 1;
        this.score = 0;
        this.labelscore.string = "0";
        for(var key in this.girdArr){
            this.girdArr[key].destroy();
        }
    }

    
}
